# plot the output of blogc

import sys
import matplotlib.pyplot as plt
from optparse import OptionParser

def main():
  parser = OptionParser()
  parser.add_option("-l", "--legloc", dest="legloc", default="upper right",
                    help = "location of the legend")

  parser.add_option("-t", "--title", dest="title", default=" ",
                    help = "title of the chart")

  parser.add_option("-q", "--query", dest="query", default=None,
                    help = "optional comma separated list of query names")
  
  #parser.add_options("-t", "--title", dest="title", default=" ",
  #                   help = "title of the charts")
  
  (options, args) = parser.parse_args()
  
  if (len(args) != 1):
    print "Usage: python plotblog.py [options] <output-file>"
    parser.print_usage()
    sys.exit(1)

  ENGINE_BLOGC, ENGINE_BLOG = range(2)
  engine = None
  for line in open(args[0]):
    line = line.rstrip()

    if engine is None:
      if line.startswith("blogc"):
        engine = ENGINE_BLOGC
        results = {}
        samples = []
      else:
        print "Unsupported engine:", line
        sys.exit(2)

    elif engine is ENGINE_BLOGC:
      if line.startswith("Samples done"):
        num_samples = int(line.split()[2][:-1])
        samples.append(num_samples)
        
      elif line.startswith(" Query"):
        words = line.split()
        query_name = words[0][:-1]
        
        if query_name not in results:
          results[query_name] = {}

        query_results = results[query_name]

        # discrete results
        if words[1][0] == "{":
          for widx in range(1, len(words), 2):
            if widx == 1:
              label = words[widx][1:-1]
            else:
              label = words[widx][:-1]
            try:
              value = float(words[widx+1][:-1])
            except:
              value = 0

            if label not in query_results:
              query_results[label] = [0 for _ in range(len(samples)-1)]

            query_results[label].append(value)
        elif words[1] == "P(null)":

          for widx in range(1, len(words), 2):
            label = words[widx]
            try:
              value = float(words[widx+1])
            except:
              value = 0

            if label not in query_results:
              query_results[label] = []

            query_results[label].append(value)
        else:
          print "Error: unexpected query output:", line
          sys.exit(3)

      else:
        print "Error: unexpected line:", line
        sys.exit(4)

  for query_name, query_results in results.iteritems():
    if options.query is not None \
           and query_name not in options.query.split(","):
      print "Skipping", query_name
      continue
    
    plt.figure()
    plt.title(query_name + " " + options.title)
    cnum = 0
    for label, values in query_results.iteritems():
      plt.plot(samples, values, label=label, linewidth=3)
      cnum += 1
    plt.xlabel("Samples")
    plt.legend(loc=options.legloc)

  plt.show()
  
if __name__ == "__main__":
  main()
  
